#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 设置根节点
    ui->treeWidget->setHeaderLabel(QString("动物"));

    // 添加顶点
    QTreeWidgetItem* item1 = new QTreeWidgetItem;
    item1->setText(0,"猫");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem;
    item2->setText(0,"狗");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3 = new QTreeWidgetItem;
    item3->setText(0,"鸟");
    ui->treeWidget->addTopLevelItem(item3);
}

Widget::~Widget()
{
    delete ui;
}

// 在顶点插入
void Widget::on_pushButton_AddTop_clicked()
{
    // 获取输入框内容
    const QString& text = ui->lineEdit->text();
    if(text.isEmpty())
        return;

    // 插入顶点节点
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0,text);
    ui->treeWidget->addTopLevelItem(item);
}

// 在选中节点插入子节点
void Widget::on_pushButton_AddCurrent_clicked()
{
    // 获取输入框内容
    const QString& text = ui->lineEdit->text();
    if(text.isEmpty())
        return;

    // 判断选中节点是否为空
    QTreeWidgetItem* current = ui->treeWidget->currentItem();
    if(current == nullptr)
        return;

    // 插入节点
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0,text);
    current->addChild(item);

    // 展开父节点
    current->setExpanded(true);
}

// 删除所选节点
void Widget::on_pushButton_Take_clicked()
{
    // 获取当前节点
    QTreeWidgetItem* current = ui->treeWidget->currentItem();
    if(current == nullptr)
        return;

    // 获取当前父节点
    QTreeWidgetItem* parent = current->parent();

    // 删除当前节点
    if(parent == nullptr)   // 为空，则直接删除所有子节点
    {
        int index = ui->treeWidget->indexOfTopLevelItem(current);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else                    // 不为空，则通过父节点删除子节点
    {
        parent->removeChild(current);
    }
}
